import { type AxiosPromise } from "axios";
import { post, get } from "@/utils/request";
import { useMutation, useQueryClient } from "@tanstack/react-query";

export const roleKeys = {
  all: () => ["roles"],
  rolesTableTree: () => ["rolesTableTree"],
  rolesSelectTree: () => ["rolesSelectTree"],
};
// 角色列表
export const roles = (): AxiosPromise => {
  return get("/roles?format=select&limit=9999", {});
};
// 角色树形结构（表格使用）
export const rolesTableTree = (): AxiosPromise => {
  return get("/roles?format=table_tree&limit=9999", {});
};
// 角色树形结构（下拉框使用）
export const rolesSelectTree = (): AxiosPromise => {
  return get("/roles?format=tree&limit=9999", {});
};

export interface RoleData {
  [key: string]: unknown;
}

export const roleAdd = (data: RoleData): AxiosPromise => {
  return post("/roles", data);
};
export const roleEdit = (data: RoleData): AxiosPromise => {
  return post("/roles/update", data);
};
export const roleDel = (data: RoleData): AxiosPromise => {
  return post("/roles/delete", data);
};

export function useRoleAdd() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (newData: RoleData) => {
      await queryClient.cancelQueries({ queryKey: roleKeys.rolesTableTree() });
      return roleAdd(newData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: roleKeys.rolesTableTree() });
    },
  });
}

export function useRoleEdit() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: RoleData) => {
      return roleEdit(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: roleKeys.rolesTableTree() });
    },
  });
}
export function useRoleDel() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: RoleData) => {
      return roleDel(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: roleKeys.rolesTableTree() });
    },
  });
}
